package com.yhb.third.leshua;

import javax.crypto.Cipher;
import java.io.ByteArrayOutputStream;
import java.io.IOException;
import java.security.KeyFactory;
import java.security.PrivateKey;
import java.security.spec.PKCS8EncodedKeySpec;
import java.util.Base64;

/**
 * @author Daniel
 *
 */
public class RSADecryptUtil {
    // 解密最长256
    private static final Integer MAX_DECRYPT_BLOCK = 256;

    // 将Base64编码后的私钥转换成PrivateKey对象
    public static PrivateKey string2PrivateKey(String priStr) throws Exception{
        byte[] keyBytes = base642Byte(priStr);
        PKCS8EncodedKeySpec keySpec = new PKCS8EncodedKeySpec(keyBytes);
        KeyFactory keyFactory = KeyFactory.getInstance("RSA");
        PrivateKey privateKey = keyFactory.generatePrivate(keySpec);
        return privateKey;
    }

    // 私钥分段解密
    public static byte[] privateDecrypt(byte[] data, PrivateKey privateKey) throws Exception{
        Cipher cipher = Cipher.getInstance("RSA");
        cipher.init(Cipher.DECRYPT_MODE, privateKey);

        int inputLen = data.length;
        ByteArrayOutputStream out = new ByteArrayOutputStream();
        int offSet = 0;
        byte[] cache;
        int i = 0;
        // 对数据分段加密
        while (inputLen - offSet > 0) {
            if ( inputLen - offSet > MAX_DECRYPT_BLOCK) {
                cache = cipher.doFinal( data, offSet, MAX_DECRYPT_BLOCK);
            } else {
                cache = cipher.doFinal( data, offSet, inputLen - offSet);
            }
            out.write( cache, 0, cache.length);
            i++;
            offSet = i * MAX_DECRYPT_BLOCK;
        }
        byte[] encryptedData = out.toByteArray();
        out.close();
        return encryptedData;
    }

    // Base64编码转字节数组
    public static byte[] base642Byte(String base64Key) throws IOException {
        return Base64.getDecoder().decode(base64Key);
    }
    /**
     * 最终解密
     * @param message 要解密的数据
     * @param privateKeyStr 私钥
     * @return
     */
    public static String decrypt(String message, String privateKeyStr) throws Exception {
        PrivateKey privateKey = string2PrivateKey(privateKeyStr);
        byte[] base642Byte = base642Byte(message);
        byte[] privateDecrypt = privateDecrypt(base642Byte, privateKey);
        return new String(privateDecrypt);
    }

    public static void main(String[] args) throws Ex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ywPP+UUDkKMdbroFxqZgDQCLzTe/Gb9VJ8t7zF5Xtvfvfhx9P3YivgdlOvSla3nFM1gAFasNGuV5T6FKwM3BrmmPCPoFGZ5R2u57u3Kh+JCV8/8EJfK8PxnunXjfkWRUSONhEEO6Ug6pUqBdNGQ/1utKXQE49TwGYtqlJkqEcZ30kXVChsvhK+nNFIOLG0ILolAF+DSj8cigZWIpSvvTpet97JfnMgHM8MYs31+ig0ZIosam7GLvYgCT9/kHcX/QAaSnNckWs7BP7OG8mYD6RdAsqw/ow2jhcLZpX+ksuxdvckKVCAqm7VZb2L8Vla00rWc1rV3JqpemlW6/U5LX3+FiibzKY+4QM2jNi996cEb1oqBLYpdQr8oP";
        //解密后的明文
        System.out.println("解密后的明文: " + decrypt(message, privateKeyStr));
    }
}
